<template>
    <div style="width: 100%">
        <el-button type="primary" v-if="$props.isEdit && $props.status === 1" :icon="Plus" @click="popupShow = true">添加产品</el-button>
        <el-button type="danger" v-if="$props.isEdit && $props.status === 1" :icon="Delete" @click="deleteProduct">删除</el-button>
        <el-scrollbar v-loading="loading">
            <el-card class="m-3">
                <el-row :gutter="6" style="padding-right: 20px;">
                    <el-col :span="2" align="center" class="col-title" v-if="$props.isEdit && $props.status === 1">选择</el-col>
                    <el-col :span="6" align="center" class="col-title">标题</el-col>
                    <el-col :span="2" align="center" class="col-title">封面</el-col>
                    <el-col :span="3" align="center" class="col-title">商品金额</el-col>
                    <el-col :span="3" align="center" class="col-title">需求数量</el-col>
                    <el-col :span="3" align="center" class="col-title">采购数量</el-col>
                    <el-col :span="3" align="center" class="col-title" v-if="$props.status === 2 || $props.status === 3">入库数量</el-col>
                    <el-col :span="3" align="center" class="col-title">单价</el-col>
                </el-row>
                <el-collapse v-model="activeName" v-if="data && data.length > 0">
                    <el-collapse-item :name="item.id" v-for="(item,index) in data" :key="item.id">
                        <template #title>
                            <div style="width: 100%;height: 70px;align-items: center;">
                                <el-row :gutter="6" style="height: 70px;">
                                    <el-col :span="2" align="center" class="col-item" v-if="$props.isEdit && $props.status === 1">
                                        <el-checkbox v-model="item.checked" size="large" @click.stop="handleCheckboxChange(index,item.checked)" />
                                    </el-col>
                                    <el-col :span="6" align="center" class="col-item"><div>{{ item.title }}</div></el-col>
                                    <el-col :span="2" align="center" class="col-item">
                                        <el-image
                                            @click.stop
                                            :src="item.thumb"
                                            fit="cover"
                                            class="w-10 h-10"
                                            :preview-src-list="[item.thumb]"
                                            preview-teleported
                                            hide-on-click-modal
                                        ></el-image>
                                    </el-col>
                                    <el-col :span="3" align="center" class="col-item"><div>{{ item.money_price }}</div></el-col>
                                    <el-col :span="3" align="center" class="col-item"><div>{{ item.xq_num }}</div></el-col>
                                </el-row>
                            </div>
                        </template>
                        <div style="background-color: #FAFAFA;padding-right: 20px;">
                            <el-row :gutter="6" style="height: 70px;" v-for="(sku_item,sku_index) in item.skus" :key="sku_index">
                                <el-col :span="2" align="center" class="col-item" v-if="$props.isEdit && $props.status === 1">
                                    <el-checkbox v-model="sku_item.checked" size="large" @click.stop="handleSkuCheckboxChange(index,sku_index,sku_item.checked)" />
                                </el-col>
                                <el-col :span="6" align="center" class="col-item"><div>{{ sku_item.title }}</div></el-col>
                                <el-col :span="2" align="center" class="col-item">
                                    <el-image
                                        :src="sku_item.thumb"
                                        fit="cover"
                                        class="w-10 h-10"
                                        :preview-src-list="[sku_item.thumb]"
                                        preview-teleported
                                        hide-on-click-modal
                                    ></el-image>
                                </el-col>
                                <el-col :span="3" align="center" class="col-item"><div>{{ sku_item.money_price }}</div></el-col>
                                <el-col :span="3" align="center" class="col-item"><div>{{ sku_item.xq_num }}</div></el-col>
                                <el-col :span="3" align="center" class="col-item">
                                    <span style="color: var(--el-color-danger);margin-right: 5px;" v-if="$props.isEdit">*</span>
                                    <el-input
                                        v-model="sku_item.actual_quantity"
                                        style="width: 100px"
                                        placeholder="采购数量"
                                        :disabled="!$props.isEdit || $props.status === 2 || $props.status === 3"
                                        @change="inputQuantity(index,sku_index,$event)"
                                    />
                                </el-col>
                                <el-col :span="3" align="center" class="col-item" v-if="$props.status === 2 || $props.status === 3">
                                    <span style="color: var(--el-color-danger);margin-right: 5px;" v-if="$props.isEdit">*</span>
                                    <el-input
                                        v-model="sku_item.plan_quantity"
                                        style="width: 100px"
                                        placeholder="入库数量"
                                        @change="inputWarehousNum(index,sku_index,$event)"
                                    />
                                </el-col>
                                <el-col :span="3" align="center" class="col-item">
                                    <span style="color: var(--el-color-danger);margin-right: 5px;" v-if="$props.isEdit">*</span>
                                    <el-input
                                        v-model="sku_item.price"
                                        style="width: 100px"
                                        placeholder="单价"
                                        :disabled="!$props.isEdit || $props.status === 2 || $props.status === 3"
                                        @change="inputUnivalence(index,sku_index,$event)"
                                    />
                                </el-col>
                            </el-row>
                        </div>
                    </el-collapse-item>
                </el-collapse>
                <div v-else class="empty-data">
                    暂无数据
                </div>
            </el-card>
        </el-scrollbar>

        <!-- 添加产品弹窗 -->
        <addProduct v-bind="$attrs" :modelValue="popupShow" @close="(value: any) => (popupShow = value)" ref="childRef" :data="data"
            :purchaserList="props.purchaserList" @addProduct="addProducts"></addProduct>
    </div>
</template>

<script setup lang="ts">
import { ref, nextTick, inject, computed , watch , onMounted } from 'vue'
import createAxios from '/@/utils/axios'
import { Plus, Delete, CloseBold } from '@element-plus/icons-vue'
import type { ElTable, TableInstance } from 'element-plus'
import addProduct from './addProduct.vue'
const childRef = ref(); //产品弹窗组件

const props = defineProps({
    purchaserList: Array, //采购员列表
    detail_id: Number, //采购明细id
    isEdit: Boolean, //是否可编辑
    status: Number, //1添加与编辑 2入库 3异常处理
})

const emits = defineEmits(['updateData'])

let activeName: any = ref([])
let data: any = ref([]) //产品数据   
let popupShow = ref(true) //是否打开添加产品弹窗
let dateDetail: any = ref([]) //商品明细
let loading = ref(false) // 表单加载状态
let oldDateDetail: any = ref([]) //编辑进来时原来的商品明细(为了将detail_id记录)

watch(
    () => data.value,
    (newVal,oldVal) => {
        if(newVal && oldVal.length == 0) {
            //折叠全部展开
            activeName.value = []
            data.value.forEach((item: any) => {
                activeName.value.push(item.id)
            })
            return
        }
        newVal.forEach((item: any) => {
            let result = oldVal.find((item2:any) => {
                return item2.id == item.id
            })
            if(!result) {
                activeName.value.push(item.id)
            }
        })
        
    }
);

//输入入库数量
const inputWarehousNum = (index: any,sku_index: any,val: any) => {
    dateDetail.value[index].sku_list[sku_index].plan_quantity = val
    emits('updateData',dateDetail.value)
}

//输入采购数量
const inputQuantity = (index: any,sku_index: any,val: any) => {
    dateDetail.value[index].sku_list[sku_index].actual_quantity = val
    emits('updateData',dateDetail.value)
}

//输入单价
const inputUnivalence = (index: any,sku_index: any,val: any) => {
    dateDetail.value[index].sku_list[sku_index].price = val
    emits('updateData',dateDetail.value)
}

//删除产品
const deleteProduct = () => {
    //将勾选的产品删除
    let dataTemp: any=[]
    data.value.forEach((item:any) => {
        if(!item.checked) {
            let dataSkuTemp:any = []
            dataTemp.push(item)
            item.skus.forEach((sku_item:any) => {
                if(!sku_item.checked) {
                    dataSkuTemp.push(sku_item)
                }
            });
            if(dataTemp[dataTemp.length-1]) {
                dataTemp[dataTemp.length-1].skus = dataSkuTemp
            }
        } else {
            //取消添加产品弹窗内表格的对应勾选并删除选择的数据
            childRef.value!.getSelectionRows(item,false)
        }
    })
    data.value = dataTemp
    console.log(data.value,"删除后的data");
    updateData()
}


//添加产品
const addProducts = (arr: any) => {
    data.value = arr.value
    console.log('父组件的data',data);
    updateData()
}

//添加产品时赋值
const updateData = () => {
    dateDetail.value = []
    
    //data添加时来自子组件，编辑时来自父组件和子组件
    data.value.forEach((item:any,index:any) => {
        dateDetail.value.push({
            product_id: props.detail_id ? item.product_id : item.id,
            product_title: item.title,
            remark: item.remark,
            thumb: item.thumb,
            money_price: item.money_price,
            sku_list: []
        })
        item.skus.forEach((sku_item: any) => {
            dateDetail.value[index].sku_list.push({
                demand_sku_id: sku_item.id,
                detail_id:sku_item.detail_id,
                uuid:sku_item.uuid,
                xq_id: sku_item.xq_id,
                plan_quantity: sku_item.plan_quantity,
                actual_quantity: sku_item.actual_quantity,
                price: sku_item.price,
                sku_title: sku_item.title,
                money_price: sku_item.money_price,
                thumb: sku_item.thumb
            })
        });
    });
    //新的dateDetail对比旧的oldDateDetail添加detail_id
    oldDateDetail.value.forEach((item :any)=> {
        dateDetail.value.forEach((element :any) => {
            element.sku_list.forEach((element2 :any) => {
                if(element2.demand_sku_id == item.demand_sku_id) {
                    element2.detail_id = item.detail_id
                }
            })
        });
    })

    emits('updateData',dateDetail.value)
}

//选中单元格
const handleCheckboxChange = (index: any, checked: Boolean) => {
    // 处理checkbox变化的逻辑
    data.value[index].skus.forEach((element :any) => {
        element.checked = !checked
    });
}

//选中SKU单元格
const handleSkuCheckboxChange = (index: any,sku_index: any,checked: any) => {
    // 处理checkbox变化的逻辑
    setTimeout(() => {
        let flag = data.value[index].skus.every((item :any) => {
            return item.checked
        })
        if(flag) {
            data.value[index].checked = true
        } else {
            data.value[index].checked = false
        }
    }, 100);
}

// 获取商品ID获取商品信息(仅查看详情时使用)
const getProductInfo = () => {
    loading.value = true
    createAxios({ url: '/admin/xmwms.purchase.Order/detail', method: 'get', params: { id: props.detail_id } }).then((res) => {
        if (res.code === 1) {
            data.value = res.data.detail
            loading.value = false
            // //展开所有折叠
            // data.value.forEach(item => {
            //     activeName.value.push(item.id)
            // })
        }
    })
}

onMounted(() => {
    popupShow.value = false
    if(props.detail_id) {
        getProductInfo()
    }
})

defineExpose({
    data,
    dateDetail,
    oldDateDetail,
    updateData,
})
</script>

<style scoped lang="scss">
.empty-data {
    color: var(--el-text-color-secondary);
    text-align: center;
    border-top: 1px solid #e5e7eb;
    border-bottom: 1px solid #e5e7eb;
    padding: 15px;
}
.col-title {
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 10px
}
:deep(.el-collapse-item__header) {
    height: 70px;
}

:deep(.el-collapse-item__content) {
    padding-bottom: 0!important;
}

.col-item {
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
